const Image = require('../models/imageModel')
const catchAsync = require('../utils/catchAsync')
const AppError = require('../utils/appError')
const { uploadFile } = require('../utils/ossUtil')

/**
 * 上传图片
 */
exports.uploadImage = catchAsync(async (req, res, next) => {
  // 检查请求中是否包含文件
  if (!req.file) {
    return next(new AppError('没有上传任何文件', 400))
  }

  const fileResult = await uploadFile(req.file)

  const newImage = await Image.create({ filename: fileResult.filename, url: fileResult.url })

  res.status(201).json({
    status: 'success',
    message: '图片上传成功',
    data: newImage,
  })
})

/**
 * 分页获取图片
 */
exports.pageImages = catchAsync(async (req, res, next) => {
  const pageNum = +req.query.pageNum || 1
  const pageSize = +req.query.pageSize || 10
  const skip = (pageNum - 1) * pageSize

  const [images, totalItems] = await Promise.all([
    Image.find().sort({ createdAt: -1 }).skip(skip).limit(pageSize),
    Image.countDocuments(),
  ])

  res.status(200).json({
    status: 'success',
    data: {
      total: totalItems,
      currentPage: pageNum,
      pageSize: pageSize,
      totalPages: Math.ceil(totalItems / pageSize),
      images,
    },
  })
})

/**
 * 删除图片
 * 只从数据库中删除
 */
exports.deleteImage = catchAsync(async (req, res, next) => {
  const { id } = req.params

  if (!id) {
    return next(new AppError('请提供要删除的图片ID', 400))
  }

  const deletedImage = await Image.findByIdAndDelete(id)

  if (!deletedImage) {
    return next(new AppError('未找到该图片，可能已被删除', 404))
  }

  res.status(200).json({
    status: 'success',
    message: '图片已删除',
  })
})
